package com.Q04;

import com.common.ListNode;
import com.common.TreeNode;

import java.util.Deque;
import java.util.LinkedList;

/**
 * @version v1.0.0
 * 创建时间：2022/6/30 15:07
 */
public class Q04_03 {
    public ListNode[] listOfDepth(TreeNode tree) {
        if (tree ==null) return null;
        // 广度优先遍历
        Deque<TreeNode> level = new LinkedList<>();
        level.add(tree);
        LinkedList<ListNode> levelList = new LinkedList<>();
        while(!level.isEmpty()){
            Deque<TreeNode> temp = new LinkedList<>();
            ListNode levelHead = new ListNode(0);
            ListNode p = levelHead;
            while (!level.isEmpty()){
                TreeNode treeNode = level.removeFirst();
                p.next = new ListNode(treeNode.val);
                p = p.next;
                if (treeNode.left!=null)
                    temp.add(treeNode.left);
                if (treeNode.right!=null)
                    temp.add(treeNode.right);
            }
            levelList.add(levelHead.next);
            level =temp;
        }

        ListNode[] result = levelList.toArray(new ListNode[]{});
        return result;
    }
}
